package com.practice.communication.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class ClientHandler implements Runnable{
	
	private String ip;
	private int port;
	private Selector selector;
	private SocketChannel socketChannel;
	private volatile boolean started;

	public ClientHandler(String ip, int port) {
		this.ip = ip;
		this.port = port;
		
		try {
			//创建选择器
			selector = Selector.open();
			
			//打开监听通道
			socketChannel = SocketChannel.open();
			
			socketChannel.configureBlocking(false);
			started = true;
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	public void stop() {
		started = false;
	}

	@Override
	public void run() {
		try {
			doConnect();
		} catch(Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
		
		//循环遍历selector
		while(started) {
			try {
				//无论是否读写时间发生，selector每隔1秒被唤醒一次
				selector.select(1000);
				
				//阻塞，只有当至少一个注册事件发生的时候才会继续
				Set<SelectionKey> keys = selector.selectedKeys();
				
				Iterator<SelectionKey> it = keys.iterator();
				SelectionKey key = null;
				while(it.hasNext()) {
					key = it.next();
					it.remove();
					try {
						handlerInput(key);
					} catch(Exception e) {
						if (key != null) {
							key.cancel();
							if (key.channel() != null) {
								key.channel().close();
							}
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if (selector != null) {
			try {
				selector.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void handlerInput(SelectionKey key) throws IOException {
		if (key.isValid()) {
			SocketChannel sc = (SocketChannel)key.channel();
			if (key.isConnectable()) {
				if (sc.finishConnect());
				else System.exit(1);
			}
			
			if (key.isReadable()) {
				ByteBuffer buffer = ByteBuffer.allocate(1024);
				int readBytes = sc.read(buffer);
				if (readBytes > 0) {
					buffer.flip();
					byte[] bytes = new byte[buffer.remaining()];
					buffer.get(bytes);
					String result = new String(bytes, "UTF-8");
					System.out.println("客户端收到消息：" + result);
				} else if (readBytes < 0) {
					key.cancel();
					sc.close();
				}
			}
		}
	}

	private void doConnect() throws IOException {
		if (socketChannel.connect(new InetSocketAddress(ip, port)));
		else socketChannel.register(selector, SelectionKey.OP_CONNECT);
	}

	public void sendMsg(String msg) throws IOException {
		socketChannel.register(selector, SelectionKey.OP_READ);
		doWrite(socketChannel, msg);
	}

	private void doWrite(SocketChannel channel, String msg) throws IOException {
		//将消息编码为字节数组
		byte[] bytes = msg.getBytes();
		
		//根据数组容量创建ByteBuffer
		ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
		
		//将字节数组复制到缓冲区
		buffer.put(bytes);
		
		//flip操作
		buffer.flip();
		
		//发送缓冲区的字节数组
		channel.write(buffer);
		
		//****此处不含处理“写半包”的代码
	}

}
